const express=require('express');
const loginModel=require('../../Model/login');
var router = express.Router();
const md5=require('md5');
const checkMiddleleware=require('../../middleware/check')

router.get('/',(req,res)=>{
    res.redirect('/login');
})

router.get('/login',(req,res)=>{
   res.render('auth/login');
});

router.post('/login',(req,res)=>{
   console.log(req.body);
    loginModel.create({...req.body,password:md5(req.body.password)},(err,data)=>{
        if(err)
        {
            return res.status(500).send('出错了');
        }
        res.render('success',{msg:'注册成功',url:'/sign'});
    });
 });

 router.get('/sign',checkMiddleleware,(req,res)=>{
    res.render('auth/sign');
 });

 router.post('/sign',checkMiddleleware,(req,res)=>{
let {username,password}=req.body;

loginModel.findOne({username:username,password:md5(password)},(err,data)=>{
if(err)
{
    res.status(500).send('登录失败');
}
else{
    if(!data){
        res.send("账号或密码错误")
    }
    else{
        req.session.username=data.username;
        req.session._id=data._id;
        res.send('测试积极');
    }
}
console.log(data);



})

 });

 router.get('/logout',(req,res)=>{
    req.session.destroy(()=>{
        res.render('success',{msg:'退出成功',url:'/login'})
    })
 })

module.exports=router;

